const { contextBridge, ipcRenderer } = require("electron/renderer");

contextBridge.exposeInMainWorld("versions", {
  node: () => process.versions.node,
  chrome: () => process.versions.chrome,
  electron: () => process.versions.electron,
});

contextBridge.exposeInMainWorld("electronAPI", {
  setTitle: (title) => ipcRenderer.send("set-title", title),
  onUpdateCounter: (callback) =>
    ipcRenderer.on("update-counter", (_event, value) => callback(value)),
  toggle: () => ipcRenderer.invoke("dark-mode:toggle"),
  system: () => ipcRenderer.invoke("dark-mode:system"),
  startDrag: (fileName) => ipcRenderer.send("ondragstart", fileName),
  onDragEnd: (callback) => ipcRenderer.on("ondragend", callback),
});

// MessageChannel
const windowLoaded = new Promise((resolve) => {
  window.onload = resolve;
});
ipcRenderer.on("main-world-port", async (event) => {
  await windowLoaded;
  // 我们使用 window.postMessage 将端口
  // 发送到主进程
  window.postMessage("main-world-port", "*", event.ports);
});
